import React, { useCallback, useMemo, useState, useEffect } from 'react'
import { NavBar, DotLoading, CapsuleTabs, Card, Grid } from 'antd-mobile'
import { SearchBar, Empty } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import axios from '../../api/http'

function Index() {
  const nav = useNavigate()
  const [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(false)
  const [pageCode, setPageCode] = useState(1)
  const pageSize = 10
  const [list, setList] = useState<any[]>([])
  const [activeTab, setActiveTab] = useState('all')
  const [searchHistory, setSearchHistory] = useState<string[]>([])
  const [hotKeywords, setHotKeywords] = useState<string[]>([])

  const canSearch = useMemo(() => keyword.trim().length > 0, [keyword])

  // 搜索分类配置
  const searchCategories = [
    { key: 'all', title: '全部' },
    { key: 'doctor', title: '医生' },
    { key: 'hospital', title: '医院' },
    { key: 'medicine', title: '药品' },
    { key: 'disease', title: '疾病' }
  ]

  // 热门搜索关键词
  useEffect(() => {
    setHotKeywords(['感冒', '发烧', '咳嗽', '头痛', '胃痛', '失眠', '高血压', '糖尿病'])
    
    // 从localStorage获取搜索历史
    const history = localStorage.getItem('searchHistory')
    if (history) {
      setSearchHistory(JSON.parse(history))
    }
  }, [])

  const fetchList = useCallback(async (kw: string, page: number, category: string = 'all') => {
    setLoading(true)
    try {
      const params: any = {
        pageCode: page,
        pageSize: pageSize,
        searchValue: kw.trim()
      }
      
      // 根据分类添加不同的参数
      if (category !== 'all') {
        params.type = category
      }
      
      const res: any = await axios.get('/search', { params })
      const data = (res && (res.data || res.list || res.results)) || []
      setList(Array.isArray(data) ? data : [])
    } catch (e) {
      console.error('搜索失败:', e)
      setList([])
    } finally {
      setLoading(false)
    }
  }, [])

  // 保存搜索历史
  const saveSearchHistory = useCallback((keyword: string) => {
    if (!keyword.trim()) return
    
    const newHistory = [keyword, ...searchHistory.filter(item => item !== keyword)].slice(0, 10)
    setSearchHistory(newHistory)
    localStorage.setItem('searchHistory', JSON.stringify(newHistory))
  }, [searchHistory])

  const handleSearch = useCallback(() => {
    if (!canSearch) return
    setPageCode(1)
    saveSearchHistory(keyword)
    fetchList(keyword, 1, activeTab)
  }, [canSearch, fetchList, keyword, activeTab, saveSearchHistory])

  // 点击历史搜索或热门搜索
  const handleKeywordClick = useCallback((kw: string) => {
    setKeyword(kw)
    saveSearchHistory(kw)
    setPageCode(1)
    fetchList(kw, 1, activeTab)
  }, [activeTab, fetchList, saveSearchHistory])

  // 清除搜索历史
  const clearHistory = useCallback(() => {
    setSearchHistory([])
    localStorage.removeItem('searchHistory')
  }, [])

  // 分类切换
  const handleTabChange = useCallback((key: string) => {
    setActiveTab(key)
    if (keyword.trim()) {
      setPageCode(1)
      fetchList(keyword, 1, key)
    }
  }, [keyword, fetchList])

  return (
    <div style={{background:'#f5f5f5', minHeight:'100vh'}}>
      {/* 固定的顶部区域 - 吸顶功能 */}
      <div style={{
        position:'sticky', 
        top:0, 
        zIndex:1000, 
        background:'#fff',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <NavBar onBack={() => nav(-1)} backArrow style={{borderBottom: '1px solid #f0f0f0'}}>
          搜索
        </NavBar>
        <div style={{padding:'12px 16px'}}>
          <SearchBar
            placeholder='搜索医生、医院、药品、疾病症状'
            value={keyword}
            onChange={setKeyword}
            onSearch={handleSearch}
            showCancelButton={() => true}
            cancelText='搜索'
            onCancel={handleSearch}
            clearable
            style={{
              background: '#f8f9fa',
              borderRadius: '20px'
            }}
          />
        </div>
        
        {/* 搜索分类标签页 */}
        {keyword.trim() && (
          <div style={{padding:'0 16px 12px 16px'}}>
            <CapsuleTabs activeKey={activeTab} onChange={handleTabChange}>
              {searchCategories.map(category => (
                <CapsuleTabs.Tab title={category.title} key={category.key} />
              ))}
            </CapsuleTabs>
          </div>
        )}
      </div>

      {/* 内容区域 */}
      <div style={{padding:'16px'}}>
        {loading ? (
          <div style={{display:'flex',alignItems:'center',justifyContent:'center',padding:'40px 0'}}>
            <DotLoading />
            <span style={{marginLeft:'8px', color:'#999'}}>搜索中...</span>
          </div>
        ) : list && list.length ? (
          <div>
            {/* 搜索结果统计 */}
            <div style={{marginBottom:'16px', fontSize:'14px', color:'#666'}}>
              找到 {list.length} 个相关结果
            </div>
            
            {/* 搜索结果列表 */}
            {list.map((item:any, index:number) => {
              const title = item.title || item.name || item.doctorname || '结果'
              const desc = item.description || item.summary || item.doctortitle || ''
              const type = item.type || activeTab
              const image = item.image || item.avatar || item.doctorimage
              
              return (
                <Card key={item.id || index} style={{
                  marginBottom:'12px',
                  borderRadius:'12px',
                  overflow:'hidden'
                }}>
                  <div style={{padding:'16px'}}>
                    <div style={{display:'flex', alignItems:'flex-start', gap:'12px'}}>
                      {image && (
                        <img 
                          src={image} 
                          alt="avatar"
                          style={{
                            width:'60px',
                            height:'60px',
                            borderRadius:'50%',
                            objectFit:'cover'
                          }}
                        />
                      )}
                      <div style={{flex:1, minWidth:0}}>
                        <div style={{display:'flex', alignItems:'center', gap:'8px', marginBottom:'6px'}}>
                          <div style={{fontSize:'16px',fontWeight:600, color:'#333'}}>{title}</div>
                          <span style={{
                            fontSize:'10px',
                            color:'#1677ff',
                            background:'#eaf3ff',
                            padding:'2px 6px',
                            borderRadius:'8px'
                          }}>
                            {type === 'doctor' ? '医生' : type === 'hospital' ? '医院' : type === 'medicine' ? '药品' : type === 'disease' ? '疾病' : '其他'}
                          </span>
                        </div>
                        {desc && (
                          <div style={{
                            fontSize:'13px',
                            color:'#666',
                            lineHeight:'1.4',
                            display:'-webkit-box',
                            WebkitLineClamp:2,
                            WebkitBoxOrient:'vertical',
                            overflow:'hidden'
                          }}>
                            {desc}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </Card>
              )
            })}
          </div>
        ) : keyword.trim() ? (
          <div style={{textAlign:'center', paddingTop:'40px'}}>
            <Empty description='没有找到相关结果，试试其他关键词' />
          </div>
        ) : (
          <div>
            {/* 搜索历史 */}
            {searchHistory.length > 0 && (
              <Card style={{marginBottom:'16px', borderRadius:'12px'}}>
                <div style={{padding:'16px'}}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'12px'}}>
                    <h3 style={{margin:0, fontSize:'16px', color:'#333'}}>搜索历史</h3>
                    <span 
                      onClick={clearHistory}
                      style={{fontSize:'12px', color:'#999', cursor:'pointer'}}
                    >
                      清除
                    </span>
                  </div>
                  <div style={{display:'flex', flexWrap:'wrap', gap:'8px'}}>
                    {searchHistory.map((item, index) => (
                      <span 
                        key={index}
                        onClick={() => handleKeywordClick(item)}
                        style={{
                          fontSize:'12px',
                          color:'#666',
                          background:'#f8f9fa',
                          padding:'6px 12px',
                          borderRadius:'16px',
                          cursor:'pointer',
                          transition:'all 0.2s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = '#e9ecef'
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = '#f8f9fa'
                        }}
                      >
                        {item}
                      </span>
                    ))}
                  </div>
                </div>
              </Card>
            )}

            {/* 热门搜索 */}
            <Card style={{borderRadius:'12px'}}>
              <div style={{padding:'16px'}}>
                <h3 style={{margin:0, fontSize:'16px', color:'#333', marginBottom:'12px'}}>热门搜索</h3>
                <Grid columns={2} gap={8}>
                  {hotKeywords.map((item, index) => (
                    <Grid.Item key={index}>
                      <div 
                        onClick={() => handleKeywordClick(item)}
                        style={{
                          textAlign:'center',
                          padding:'12px 8px',
                          background:'#f8f9fa',
                          borderRadius:'8px',
                          cursor:'pointer',
                          transition:'all 0.2s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = '#e9ecef'
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = '#f8f9fa'
                        }}
                      >
                        <span style={{fontSize:'14px', color:'#333'}}>{item}</span>
                      </div>
                    </Grid.Item>
                  ))}
                </Grid>
              </div>
            </Card>
          </div>
        )}
      </div>
    </div>
  )
}

export default Index
